#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
#include <vector>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int tickets = 100;

void* start_routine(void* arg)
{
    string masg = static_cast<const char *>(arg);

    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);

        cout << masg << "->" << tickets << endl;
        --tickets;
        pthread_mutex_unlock(&mutex);
    }

    return nullptr;
}

int main()
{
    // pthread_t t1, t2;

    // pthread_create(&t1, nullptr, start_routine, (void*)"thread1");
    // pthread_create(&t2, nullptr, start_routine, (void*)"thread2");

    vector<pthread_t> vp(5);
    //pthread_t vp[5];
    for (size_t i = 0; i < 5; ++i)
    {
        char masg[64];
        snprintf(masg, sizeof(masg), "thread %d", i + 1);

        pthread_create(&vp[i], nullptr, start_routine, (void*)masg);
        usleep(1000);
    }

    while (true)
    {
        sleep(1);
        pthread_cond_broadcast(&cond);
        cout << "thread weak up ..." << endl;
    }

    // pthread_join(t1);
    // pthread_join(t2);

    for (int i = 0; i < 5; ++i)
    {
        pthread_join(vp[i], nullptr);
    }

    return 0;
}